package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.exception.PhoneCheckeErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {


    private final EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 密码进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeedDTO
     */
    @Override
    public void save(EmployeeDTO employeedDTO) {
        // 数据的验证
        // 使用正则判断手机号码是否是正确的格式
        String phone = employeedDTO.getPhone();
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            throw new PhoneCheckeErrorException(MessageConstant.PHONE_ERROR);
        }
        // TODO 大家去补全其他的数据的验证
        // 构建员工对象
       /* Employee employee = Employee.builder()
                .username(employeedDTO.getUsername())
                .name(employeedDTO.getName())
                .phone(employeedDTO.getPhone())
                .sex(employeedDTO.getSex())
                .idNumber(employeedDTO.getIdNumber())
                .status(StatusConstant.ENABLE)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .createUser(employeedDTO.getId())
                .updateUser(employeedDTO.getId())
                .password(DigestUtils.md5DigestAsHex("123456".getBytes()))
                .build();*/
        Employee employee = new Employee();
        // 对象属性拷贝
        BeanUtils.copyProperties(employeedDTO, employee);
        //设置密码，默认密码123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置当前记录的创建时间和修改时间
        // employee.setCreateTime(LocalDateTime.now());
        // employee.setUpdateTime(LocalDateTime.now());
        // 账号的默认状态为启用
        employee.setStatus(StatusConstant.ENABLE);
        // 设置当前记录的创建人，修改人,从ThreadLocal中获取
        // employee.setCreateUser(BaseContext.getCurrentId());
        // employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);
    }

    @Override
    public PageResult<Employee> pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        // 开启分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        // 设置总记录数和数据
        Long total = page.getTotal();
        List<Employee> records = page.getResult();
        // 给分页结果对象赋值
        PageResult<Employee> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setRecords(records);
        return pageResult;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }

    @Override
    public Employee getById(Long id) {
        return employeeMapper.getById(id);
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        // 获取员工的实体类
        Employee employee = new Employee();
        // 对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        // employee.setUpdateTime(LocalDateTime.now());
        // employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    public void updatePassword(PasswordEditDTO employeeLoginDTO) {
        // 根据id(从登录的信息中获取)查询员工信息
        Employee employee = employeeMapper.getById(BaseContext.getCurrentId());
        // 判断旧密码是否正确
        if (!employee.getPassword().equals(DigestUtils.md5DigestAsHex(employeeLoginDTO.getOldPassword().getBytes()))) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        // 判断用户输入的新密码和旧密码是否一致
        if (employeeLoginDTO.getNewPassword().equals(employeeLoginDTO.getOldPassword())) {
            throw new PasswordErrorException(MessageConstant.OLDPASSWORD_NEWPASSWORD_ERROR);
        }
        // 对新输入的密码加密后重新设置密码
        employee.setPassword(DigestUtils.md5DigestAsHex(employeeLoginDTO.getNewPassword().getBytes()));
        employeeMapper.update(employee);
    }

}
